package com.photographysharing.util;

import com.photographysharing.entity.Users;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {
    private static Long expiration;
    private static String secret;
    private static Map<String, Object> header;
    static {
        secret="R5G2MWtsddQAJ12dUYldSSAj35QEA0FkRT9utZEQ9T4UR10XO6iDeSFrIw1STpLyp9lE0f6P++Eq7/NhN9tJLw==";
        expiration = 30*24*60*60*1000L;
        header=new HashMap<>();
        header.put("typ", "jwt");
    }

    public static String getUserIdFromToken(HttpServletRequest request) {
        return getTokenClaim(request,"userid");
    }

    public static String getRoleFromToken(HttpServletRequest request){
        return getTokenClaim(request,"role");
    }
    public static String getEmailFromToken(HttpServletRequest request){
        return getTokenClaim(request,"email");
    }

    private static String getTokenClaim(HttpServletRequest request,String name){
        String token = request.getHeader("Authorization");

        // 检查Token是否以Bearer开头
        if (token != null && token.startsWith("Bearer ")) {
            // 去除Bearer前缀
            token = token.substring(7);

            // 解析Token
            Claims claims = Jwts.parser()
                    .setSigningKey(secret)  // 使用你的密钥进行解析
                    .parseClaimsJws(token)
                    .getBody();

            // 从Token的载荷中获取用户ID
            String value = (String) claims.getOrDefault(name,null);

            return value;
        }

        // 如果Token不存在或格式不正确，返回null或适当的错误处理
        return null;
    }

    public static String generateToken(Users user){
        Map<String, Object> claims = new HashMap<>();
        claims.put("email", user.getEmail());
        claims.put("userid",user.getId());
        claims.put("role", user.getRoleName());
        return generateToken(claims);
    }
    private  static String generateToken(Map<String, Object> claims) {
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);
        return Jwts.builder()
                .setHeader(header)
                .setClaims(claims)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

}
